package com.ng.framework.view.desktop.filters;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Arrays;
import java.util.List;

import javax.swing.JComponent;

import com.ng.framework.persistence.NGSearchParameter;
import com.ng.framework.persistence.NGSearchParameter.Type;
import com.ng.framework.persistence.NGSearchParameter.UnaryOperation;

public abstract class NGSimpleFilter<T extends JComponent> extends NGFilter {

	private static final long serialVersionUID = -3015198014017893892L;

	private Class<?> clazz;
	private String attribute;
	private Type type;
	private UnaryOperation unaryOperation;
	private String joinAttribute;
	
	private T component;
	
	public NGSimpleFilter(String name, Class<?> clazz, String attribute,
			Type type, UnaryOperation unaryOperation) {
		this(name, clazz, attribute, type, unaryOperation, null);
	}
	
	public NGSimpleFilter(String name, Class<?> clazz, String attribute,
			Type type, UnaryOperation unaryOperation, String joinAttribute) {
		super(name);
		this.clazz = clazz;
		this.attribute = attribute;
		this.type = type;
		this.unaryOperation = unaryOperation;
		this.joinAttribute = joinAttribute;
		
		this.buildGui();
	}
	
	private void buildGui() {
		this.setLayout(new GridBagLayout());
		
		this.add(this.getComponent(), new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
	}
	
	public T getComponent() {
		if(component == null) {
			this.component = this.createComponent();
		}
		return component;
	}

	protected abstract T createComponent();
	
	@Override
	public List<NGSearchParameter> getSearchParameters() {
		List<NGSearchParameter> searchParameters = null;
		
		String componentValue = this.getComponentValue(component);
		
		if(componentValue != null) {
			NGSearchParameter searchParameter;

			if(joinAttribute != null) {
				searchParameter = new NGSearchParameter(clazz, attribute, this.getComponentValue(component), type, unaryOperation, true, joinAttribute);
			} else {
				searchParameter = new NGSearchParameter(clazz, attribute, this.getComponentValue(component), type, unaryOperation);
			}
			
			searchParameters = Arrays.asList(new NGSearchParameter[] { searchParameter });
		}

		return searchParameters;
	}
	
	protected abstract String getComponentValue(T component);

	@Override
	public void setEnabled(boolean enabled) {
		super.setEnabled(enabled);
		
		this.getComponent().setEnabled(enabled);
	}
	
	

}
